package com.hz.friends.activity;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVGeoPoint;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.GroupChatActivity;
import com.hz.friends.chat.entity.IMChatMessage;
import com.hz.friends.group.CreateGroupActivity;
import com.hz.friends.serverrequest.ALEngineConfig.ALSexualOrientation;
import com.hz.friends.serverrequest.ALEngineConfig.ALUserGender;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

/**
 * 用户资料
 * 
 * @author john
 * 
 */

public class UserInfosActivity extends BaseActivity implements OnClickListener {

	private LinearLayout layoutheard1;
	private LinearLayout layoutheard2;
	private AVUser user = null;
	private LinearLayout layout_gift;
	private AQuery aq;
	private final String TAG = "UserInfosActivity";
	private TextView txv_giftcount;
	private ListView messageslistview;
	private TextView txv_messagecount;
	private TextView txv_nomessage;
	private TextView txv_nogift;
	private TextView txv_voice;
	private MediaPlayer mMediaPlayer = new MediaPlayer();
	private ImageView imv_speakanim;
	private TextView txv_shield;
	private TextView txv_attention;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_userinfo);
		init();
		initViews();
		setViews();
		initEvents();
		uploadGiftList();
		uploadMessages();
		getMessagesCount();
		getMyBandState();
		getMyFollowState();
		
	}

	@Override
	protected void init() {
		user = ((CustomApplication) getApplication()).user; // 当前用户
		aq = new AQuery(this); // 图片加载对象
	}

	@Override
	protected void initViews() {
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left); // bar左边按钮
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right); // bar右边按钮
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title); // bar标题
		imbtn_bar_right.setImageResource(R.drawable.userinfo_edit);
		imbtn_bar_right.setOnClickListener(this);
		imbtn_bar_left.setOnClickListener(this);
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		imbtn_bar_left.setVisibility(View.VISIBLE);

		layoutheard1 = (LinearLayout) findViewById(R.id.layoutheard1); // 图片展示第一排
		layoutheard2 = (LinearLayout) findViewById(R.id.layoutheard2);// 图片展示第二排
		final ImageView imv_heard = (ImageView) findViewById(R.id.imv_heard); // 头像
		LinearLayout layout_sex = (LinearLayout) findViewById(R.id.layout_sex); // 性别布局
		ImageView imv_sex = (ImageView) findViewById(R.id.imv_sex); // 性别图标
		TextView txv_age = (TextView) findViewById(R.id.txv_age); // 年龄
		TextView txv_wallet = (TextView) findViewById(R.id.txv_wallet); // 金币
		TextView txv_constell = (TextView) findViewById(R.id.txv_constell); // 星座
		TextView txv_location = (TextView) findViewById(R.id.txv_location); // 位置
		TextView txv_locationkm = (TextView) findViewById(R.id.txv_locationkm); // 位置距离
		TextView txv_locationtime = (TextView) findViewById(R.id.txv_locationtime); // 位置更新时间
		TextView txv_sexlike = (TextView) findViewById(R.id.txv_sexlike); // 性取向
		TextView txv_language = (TextView) findViewById(R.id.txv_language); // 语言
		TextView txv_signature = (TextView) findViewById(R.id.txv_signature); // 签名
		 txv_voice = (TextView) findViewById(R.id.txv_voice); // 声音
		 imv_speakanim = (ImageView) findViewById(R.id.imv_speakanim); // 声音动画

		LinearLayout layout_botom = (LinearLayout) findViewById(R.id.layout_botom);// 底部布局包含
																					// 聊天、关注、拉黑按钮
		LinearLayout layout_gogifts = (LinearLayout) findViewById(R.id.layout_gogifts);// 跳转礼物列表
		LinearLayout layout_gomessage = (LinearLayout) findViewById(R.id.layout_gomessage);// 跳转留言列表
		layout_gift = (LinearLayout) findViewById(R.id.layout_gift); // 包含礼物滚动列表
		txv_giftcount = (TextView) findViewById(R.id.txv_giftcount); // 礼物数量
		txv_nogift = (TextView) findViewById(R.id.txv_nogift); // 没有礼物提示
		txv_messagecount = (TextView) findViewById(R.id.txv_messagecount); // 消息数量
		txv_nomessage = (TextView) findViewById(R.id.txv_nomessage); // 没有留言提示
		messageslistview = (ListView) findViewById(R.id.messageslistview); // 消息listview
		TextView txv_startchat = (TextView) findViewById(R.id.txv_startchat); //  聊天按钮
				txv_attention = (TextView) findViewById(R.id.txv_attention); //  关注按钮
		        txv_shield = (TextView) findViewById(R.id.txv_shield); //  拉黑按钮

		layout_gogifts.setOnClickListener(this);
		layout_gomessage.setOnClickListener(this);
		txv_startchat.setOnClickListener(this);
		txv_attention.setOnClickListener(this);
		txv_shield.setOnClickListener(this);
		imv_heard.setOnClickListener(this);

		// 初始化页面
		AVUser curruser = AVUser.getCurrentUser();
		imbtn_bar_title.setText(user.getString("nickname"));
		if (curruser.getObjectId().equals(user.getObjectId())) {// 自己
			layout_botom.setVisibility(View.GONE);
		} else { // 其他人资料
			imbtn_bar_right.setVisibility(View.INVISIBLE);
		}

		// 填充数据
		String heardurl = user.getString("headViewURL");
		String nickname = user.getString("nickname");
		String signature = user.getString("signature");
		Double credits = user.getDouble("credits");
		Date brithday = user.getDate("brithday");
		int gender = user.getInt("gender");
		int sexualOrientation = user.getInt("sexualOrientation");
		int introductionOfVoiceOfDuration = user.getInt("introductionOfVoiceOfDuration");
		String introductionOfVoiceURL = user.getString("introductionOfVoiceURL");
		String place = user.getString("place");

		setConstellat(txv_constell, brithday);
		txv_age.setText(String.valueOf(UtilTools.getAgeByBirthday(brithday))); // 年龄
		txv_wallet.setText(String.valueOf(credits));// 金币
		if(credits == 0)
			txv_wallet.setText(String.valueOf(0));// 金币

		txv_signature.setText(signature);
		if (gender == ALUserGender.ALUserGenderOfFemale.get_value()) {// 女性
			layout_sex.setBackgroundResource(R.drawable.shape_bj_icwoman_xml);
			imv_sex.setImageResource(R.drawable.ic_woman);
		} else {// 男性
			layout_sex.setBackgroundResource(R.drawable.shape_bj_icman_xml);
			imv_sex.setImageResource(R.drawable.ic_man);
		}

		// 性取向
		if (sexualOrientation == ALSexualOrientation.ALSexualOrientationOfHomosexual
				.get_value()) {
			txv_sexlike.setText("sexualpreference:"
					+ ALSexualOrientation.ALSexualOrientationOfHomosexual
							.get_name());
		} else if (sexualOrientation == ALSexualOrientation.ALSexualOrientationOfHeterosexual
				.get_value()) {
			txv_sexlike.setText("sexualpreference:"
					+ ALSexualOrientation.ALSexualOrientationOfHeterosexual
							.get_name());

		} else if (sexualOrientation == ALSexualOrientation.ALSexualOrientationOfBisexuality
				.get_value()) {
			txv_sexlike.setText("sexualpreference:"
					+ ALSexualOrientation.ALSexualOrientationOfBisexuality
							.get_name());
		}

		// 头像
		final int width = DensityUtil.dip2px(this, 70);
		final int stroke = DensityUtil.dip2px(this, 1);
		Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
		Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(this,
				crclebitmap, width, stroke, "#eeeeee");
		imv_heard.setImageBitmap(crclestrokebitmap);
		aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
			@Override
			public void callback(String url, Bitmap bitmap, AjaxStatus status) {
				Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(
						UserInfosActivity.this, bitmap, width, stroke,
						"#eeeeee");
				imv_heard.setImageBitmap(mbitmap);
			}
		});

		//语音
		if(introductionOfVoiceOfDuration >0){
			txv_voice.setVisibility(View.VISIBLE);
			txv_voice.setText(String.valueOf(introductionOfVoiceOfDuration)+"\'\'");
			txv_voice.setTag(introductionOfVoiceURL);
		}else{
			txv_voice.setVisibility(View.GONE);
		}
		
		//位置相关
//		txv_location.setText(text)
		//距离
		AVGeoPoint togeopoint = user.getAVGeoPoint("location");
		 Date togeopointdate = user.getDate("lastUpdateLocationDate");
		setDistance(togeopoint, txv_locationkm);

		
		
		if(user.getObjectId().equals(AVUser.getCurrentUser().getObjectId())){
			txv_locationkm.setText("0 km");
		}
		
		if(togeopointdate != null){
			txv_locationtime.setText(UtilTools.getdurtionTimeFormat(togeopointdate, new Date()));
		}else{
			txv_locationtime.setText("no time");
		}
		txv_location.setText(place);
		
	}

	@Override
	protected void setViews() {
		ALUserEngine.defauleEngine().getUserAlbum(user, 8, new CallBack() {

			@Override
			public void done(Object object, AVException avexception) {
				MLog.i(TAG, "getUserAlbum  object：" + object + "  avexception:"
						+ avexception);
				if (avexception == null) {
					if (object != null && object instanceof List) {
						addTopImages((List<AVObject>) object);
					}
				} else {
					avexception.printStackTrace();
				}
			}
		});
	}

	@Override
	protected void initEvents() {
		txv_voice.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				playMusic((String)txv_voice.getTag(),imv_speakanim);				
			}
		});
	}

	/**
	 * @Description
	 * @param name
	 */
	private void playMusic(final String url, final ImageView iv_voice) {
		try {
			synchronized (mMediaPlayer) {// 清除上条消息的状态
				if (mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
				}
				iv_voice.setVisibility(View.VISIBLE);
				final AnimationDrawable voiceAnimation = (AnimationDrawable) iv_voice
						.getDrawable();
				mMediaPlayer.reset();
				mMediaPlayer.setDataSource(url);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
				voiceAnimation.start();
				mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
					public void onCompletion(MediaPlayer mp) {
						voiceAnimation.stop();
						iv_voice.setVisibility(View.INVISIBLE);
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * 设置星座
	 * 
	 * @param txv
	 * @param birthday
	 */
	private void setConstellat(TextView txv, Date birthday) {
		if (birthday == null)
			birthday = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String[] strs = sdf.format(birthday).split("-");
		String constell = UtilTools.getConstellation(Integer.parseInt(strs[1]),
				Integer.parseInt(strs[2]));
		txv.setText("constellation:" + constell);
	}

	/**
	 * 填充顶部图片数据
	 */
	private void addTopImages(List<AVObject> piclist) {
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int mScreenWidth = metric.widthPixels;
		int offset = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 11 * 2 + 6 * 3, getResources()
						.getDisplayMetrics());
		int rightmargin = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 6, getResources()
						.getDisplayMetrics());
		final int radius = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 6, getResources()
						.getDisplayMetrics());
		final int width = (mScreenWidth - offset) / 4;
		// Bitmap bitmap = BitmapUtils.createRoundConerImage(BitmapFactory
		// .decodeResource(getResources(), R.drawable.test_pic5), width,
		// radius);
		for (int i = 0; i < piclist.size(); i++) {
			final String url = piclist.get(i).getString("url");
			final ImageView mimageview = new ImageView(this);
			// mimageview.setImageResource(R.drawable.test_pic5);
			// mimageview.setImageBitmap(bitmap);
			mimageview.setScaleType(ScaleType.FIT_CENTER);
			mimageview.setBackgroundResource(R.drawable.shape_userinfo_pic_bj);
			aq.id(mimageview).image(url, true, true, 0, 0,
					new BitmapAjaxCallback() {
						protected void callback(String url, ImageView iv,
								Bitmap bm, AjaxStatus status) {
                            if(bm != null)
                            {
                            	 Bitmap bitmap = BitmapUtils.createRoundConerImage(bm, width,
                        		 radius);
                            	 iv.setImageBitmap(bitmap);
                            	 iv.setBackgroundColor(Color.TRANSPARENT);
                            }
						};
					});
			LinearLayout.LayoutParams lap = new LinearLayout.LayoutParams(
					width, width);
			if (i != 3 && i != 8)
				lap.rightMargin = rightmargin;
			mimageview.setLayoutParams(lap);
			if (i <= 3)
				layoutheard1.addView(mimageview);
			else
				layoutheard2.addView(mimageview);
			mimageview.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent largeintent = new Intent(UserInfosActivity.this, BigImageActivity.class);
						largeintent.putExtra("imageUrl", url);
					startActivity(largeintent);					
				}
			});
			

		}

	}

	/**
	 * 获取礼物列表
	 */
	private void uploadGiftList() {
		ALUserEngine.defauleEngine().getReceivedGiftCount(user, new CallBack() {
			@Override
			public void done(Object object, AVException avexception) {
				MLog.i(TAG, "getReceivedGiftCount avexception:" + avexception
						+ "  object:" + object);
				if (avexception == null) {
					ArrayList<HashMap> maplist = (ArrayList<HashMap>) object;
					if (maplist == null || maplist.size() == 0) {
						txv_nogift.setVisibility(View.VISIBLE);
						return;
					}
					int giftnum = 0;
					for (int i = 0; i < maplist.size(); i++) {
						HashMap<String, Object> mapitem = maplist.get(i);
						Date create = (Date) mapitem.get("updatedAt"); // 礼物时间
						AVObject avobject = (AVObject) mapitem.get("gift"); // 礼物
						int number = (Integer) mapitem.get("number"); // 礼物
						String gifturl = avobject.getString("imageURL");
						int num = (Integer) mapitem.get("number");
						giftnum += num;
//						if (i > 2)
//							continue;
						View view = LayoutInflater.from(UserInfosActivity.this) // 一个礼物布局
								.inflate(R.layout.userinfos_giftitem, null);
						ImageView imv_gft1 = (ImageView) view
								.findViewById(R.id.imv_gft1);
						TextView txv_gifttime = (TextView) view
								.findViewById(R.id.txv_gifttime);
						TextView txv_giftname = (TextView) view
								.findViewById(R.id.txv_giftname);
						aq.id(imv_gft1).image(gifturl, true, true);
//						setGiftTime(txv_gifttime, create);
						txv_gifttime.setText(String.valueOf(num));
						txv_giftname.setText(avobject.getString("name"));
						layout_gift.addView(view);

					}
					txv_giftcount.setText(String.valueOf(giftnum));
					if (giftnum == 0) {
						txv_nogift.setVisibility(View.VISIBLE);
					}
				} else {
					avexception.printStackTrace();
				}
			}
		});
	}

	/**
	 * 获取消息数据
	 */
	private void uploadMessages() {
		ALUserEngine.defauleEngine().getMessageOfBBSList(user, 2, 0, true,
				new CallBack() {
					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "getMessageOfBBSList avexception:"
								+ avexception + "  object:" + object);
						if (avexception == null) {
							List<AVObject> list = (List<AVObject>) object;
							if (list == null || list.size() == 0) {
								txv_nomessage.setVisibility(View.VISIBLE);
								return;
							}
							MessageAdpter adpter = new MessageAdpter(
									UserInfosActivity.this, list);
							messageslistview.setAdapter(adpter);
							setListViewHeightBasedOnChildren(messageslistview);
						} else {
							avexception.printStackTrace();
						}
					}
				});
	}

	/**
	 * 获取消息总数
	 */
	private void getMessagesCount() {
		ALUserEngine.defauleEngine().getMessageOfBBSCount(user, new CallBack() {
			@Override
			public void done(Object object, AVException avexception) {
				if (avexception == null) {
					txv_messagecount.setText(String.valueOf((Integer) object));
				} else {
					avexception.printStackTrace();
				}
			}
		});
	}
//添加关注
	private void addFollow(final AVUser avuser, final TextView txv) {
		if (txv.getTag() != null) {// 移除关注
			ALUserEngine.defauleEngine().removeFollow(avuser,
					new CallBack() {

						@Override
						public void done(Object object,
								AVException avexception) {
							if (avexception == null) {
								showSysToast("取消关注成功");
								txv.setText("Attention");
								txv.setTag(null);
							} else {
								showSysToast("取消关注失败");
								avexception.printStackTrace();
							}
						}
					});
		} else {// 添加关注
			ALUserEngine.defauleEngine().addFollow(avuser, null,
					new CallBack() {

						@Override
						public void done(Object object,
								AVException avexception) {
							if (avexception == null) {
								showSysToast("关注成功");
								txv.setText("Cancel");
								txv.setTag("1");
							} else {
								showSysToast("关注失败");
								avexception.printStackTrace();
							}
						}
					});
		}

	}
	
	
	//拉黑
	private void addSheild(final AVUser avuser, final TextView txv) {
		if (txv.getTag() != null) {// 取消拉黑
			ALUserEngine.defauleEngine().removeBanToUser(avuser,
					new CallBack() {

						@Override
						public void done(Object object,
								AVException avexception) {
							MLog.i(TAG, "====removeBanToUser object:"+object+" avexception:"+avexception);
							if (avexception == null) {
								showSysToast("取消黑名单成功");
								txv.setText("Shield");
								txv.setTag(null);
							} else {
								showSysToast("取消失败");
								avexception.printStackTrace();
							}
						}
					});
		} else {// 拉黑
			ALUserEngine.defauleEngine().addBanToUser(avuser,
					new CallBack() {

						@Override
						public void done(Object object,
								AVException avexception) {
							MLog.i(TAG, "====addBanToUser object:"+object+" avexception:"+avexception);
							if (avexception == null) {
								showSysToast("加入黑名单成功");
								txv.setText("Cancel");
								txv.setTag("1");
							} else {
								showSysToast("加入黑名单失败");
								avexception.printStackTrace();
							}
						}
					});
		}

	}
	private void getMyBandState(){
		ALUserEngine.defauleEngine().isBanByMyWithUser(user, new CallBack() {
			
			@Override
			public void done(Object object, AVException avexception) {
				MLog.i(TAG, "===getMyBandState===object:"+object+" avexception:"+avexception);
                  if(avexception == null){
                	  boolean flag =   (Boolean) object;
                	  if(flag){//已拉黑
                		  txv_shield.setText("Cancel");
                		  txv_shield.setTag("1");
                	  }else{//未拉黑
                		  txv_shield.setText("Shield");
                		  txv_shield.setTag(null);
                	  }
                  }else{
                	  avexception.printStackTrace();
                  }		
			}
		});
	}
	
	private void getMyFollowState(){
		List<AVUser> userlist = new ArrayList<AVUser>();
		userlist.add(user);
		ALUserEngine.defauleEngine().isMyFollowee(userlist, new CallBack() {
			
			@Override
			public void done(Object object, AVException avexception) {
				MLog.i(TAG, "====getMyFollowState==object:"+object+" avexception:"+avexception);
                  if(avexception == null){
                	  List list = (List) object;
                	  if(list == null || list.size() == 0){//未关注
                		  txv_attention.setText("Attention");
                		  txv_attention.setTag(null);
                	  }else{//已关注
                		  txv_attention.setText("Cancel");
                		  txv_attention.setTag("1");
                	  }
                  }else{
                	  avexception.printStackTrace();
                  }		
			}
		});
	}
	
	/**
	 * 设置礼物时间显示格式
	 * 
	 * @param txv
	 * @param date
	 */
	private void setGiftTime(TextView txv, Date date) {
		Date currdate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (sdf.format(currdate).equals(sdf.format(date))) {// 同一天
			int hour = currdate.getHours() - date.getHours();
			if (hour == 0) {
				int min = currdate.getMinutes() - date.getMinutes();
				txv.setText(min + " mins ago");
			} else {
				txv.setText(hour + " hours ago");
			}
		} else {
			txv.setText(sdf.format(date));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imv_heard:
			final String heardurl = user.getString("headViewURL");
			Intent largeintent = new Intent(UserInfosActivity.this,
					BigImageActivity.class);
			largeintent.putExtra("imageUrl", heardurl);
			startActivity(largeintent);
			break;
		case R.id.imbtn_bar_left://顶部左侧
			finish();
			break;
		case R.id.imbtn_bar_right: // 顶部右侧按钮
			startActivity(EditUserInfosActivity.class);
			finish();
			break;
		case R.id.layout_gogifts: // 跳转礼物列表
			// if(txv_nogift.getVisibility() == View.VISIBLE)
			// return;
//			Intent intent = new Intent(UserInfosActivity.this,
//					TheGiftActivity.class);
//			intent.putExtra("pageflag", 1);
//			startActivity(intent);
			if(user.getObjectId().equals(AVUser.getCurrentUser().getObjectId()))
				return;
			startActivity(SendGiftActivity.class);
			break;
		case R.id.layout_gomessage:// 跳转消息列表
//			if (txv_nomessage.getVisibility() == View.VISIBLE)
//				return;
			Intent msgintent = new Intent(UserInfosActivity.this,
					SubMessageActivity.class);
			msgintent.putExtra("pageflag", 1);
			startActivity(msgintent);
			break;
		case R.id.txv_startchat:
			Intent intent = new Intent(this,
					GroupChatActivity.class);
			intent.putExtra("titlename", user.getString("nickname"));
			intent.putExtra("isGroup", false);
			startActivity(intent);
			break;
		case R.id.txv_attention:
			addFollow(user, txv_attention);
			break;
		case R.id.txv_shield:
			addSheild(user, txv_shield);
			break;
		default:
			break;
		}
	}

	public   void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	
	/**
	 * 消息列表数据源
	 * 
	 * @author john
	 * 
	 */
	class MessageAdpter extends BaseAdapter {
		private List<AVObject> list = null;
		private Context context;

		public MessageAdpter(Context context, List<AVObject> list) {
			this.list = list;
			this.context = context;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			AVObject obj = list.get(position);
			AVUser fromuser = obj.getAVUser("fromUser");
			String message = obj.getString("text");
			Date create = obj.getCreatedAt();
			String nickname = fromuser == null ? "": fromuser.getString("nickname");
			String imageurl = fromuser == null ? "":fromuser.getString("headViewURL");
			AVObject giftRecorder = obj.getAVObject("giftRecorder");


			View view = LayoutInflater.from(context).inflate(
					R.layout.userinfos_messageitem, null);
			final ImageView heardview = (ImageView) view
					.findViewById(R.id.imv_msgheard);
			TextView txv_name = (TextView) view.findViewById(R.id.txv_msgname);
			TextView txv_message = (TextView) view
					.findViewById(R.id.txv_msgcontent);
			TextView txv_msgtimeafter = (TextView) view
					.findViewById(R.id.txv_msgtimeafter);
			
			LinearLayout layout_gift = (LinearLayout) view.findViewById(R.id.layout_gift);
			ImageView imv_gift = (ImageView) view.findViewById(R.id.imv_gift);
			TextView txv_giftnum = (TextView) view.findViewById(R.id.txv_giftnum);
			txv_name.setText(nickname);
			txv_message.setText(message);
			setGiftTime(txv_msgtimeafter, create);
			final int width = DensityUtil.dip2px(context, 37);
			final int stroke = DensityUtil.dip2px(context, 1);
			aq.ajax(imageurl, Bitmap.class, new AjaxCallback<Bitmap>() {
				@Override
				public void callback(String url, Bitmap bitmap,
						AjaxStatus status) {
					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(context,
							bitmap, width, stroke, "#b1d5aa");
					heardview.setImageBitmap(mbitmap);
				}
			});
			
			//礼物显示
			if(giftRecorder != null){
				AVObject gift = giftRecorder.getAVObject("gift");
				if(gift != null){
					int giftnum = giftRecorder.getInt("number");
					String gifturl = gift.getString("imageURL");
					aq.id(imv_gift).image(gifturl, true, true);
					txv_giftnum.setText("x"+String.valueOf(giftnum));
					layout_gift.setVisibility(View.VISIBLE);
				}
			
			}

			return view;
		}

	}
 
	private void setDistance(AVGeoPoint togeopoint,TextView txv) {
		AVGeoPoint mgeopoint = AVUser.getCurrentUser().getAVGeoPoint("location");
		if(mgeopoint == null || togeopoint == null){
			txv.setText("unknow");
			return;
		}
		double distan = mgeopoint.distanceInKilometersTo(togeopoint);
		  DecimalFormat  df = new DecimalFormat("#.##");
			double km = distan/1000;
		   txv.setText(df.format(km)+" km");
		
	}
 
      @Override
    protected void onDestroy() {
    	super.onDestroy();
    	mMediaPlayer.release();
    	mMediaPlayer = null;
    }
}
